import React, {useRef, useState} from 'react';
import {LoginForm, ProFormCheckbox, ProFormText} from '@ant-design/pro-components';
import {
  AlipayCircleOutlined,
  LockOutlined,
  TaobaoCircleOutlined,
  UserOutlined,
  WeiboCircleOutlined
} from '@ant-design/icons';
import {Alert, message, Tabs} from 'antd';
import {Helmet, history, useModel} from '@umijs/max';
import {flushSync} from 'react-dom';
import Register from '../Register';
import {login} from '@/services/ant-design-pro/api';
import Settings from '../../../../config/defaultSettings';
import {createStyles} from "antd-style";
import Footer from '@/components/Footer';

const useStyles = createStyles(({ token }) => ({
  action: {
    marginLeft: '8px',
    color: 'rgba(0, 0, 0, 0.2)',
    fontSize: '24px',
    verticalAlign: 'middle',
    cursor: 'pointer',
    transition: 'color 0.3s',
    '&:hover': {
      color: token.colorPrimaryActive,
    },
  },
  lang: {
    width: 42,
    height: 42,
    lineHeight: '42px',
    position: 'fixed',
    right: 16,
    borderRadius: token.borderRadius,
    ':hover': {
      backgroundColor: token.colorBgTextHover,
    },
  },
  container: {
    display: 'flex',
    flexDirection: 'column',
    minHeight: '100vh',
    backgroundImage:
      "url('https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/V-_oS6r-i7wAAAAAAAAAAAAAFl94AQBr')",
    backgroundSize: '100% 100%',
    position: 'relative',
  },
  content: {
    flex: '1',
    padding: '32px 0',
    display: 'flex',
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'center',
  },
  footer: {
    textAlign: 'center',
    padding: '16px 0',
    background: 'transparent',
  },
}));

const ActionIcons = () => {
  const { styles } = useStyles();
  return (
    <>
      <AlipayCircleOutlined key="AlipayCircleOutlined" className={styles.action} />
      <TaobaoCircleOutlined key="TaobaoCircleOutlined" className={styles.action} />
      <WeiboCircleOutlined key="WeiboCircleOutlined" className={styles.action} />
    </>
  );
};

const LoginMessage: React.FC<{ content: string }> = ({ content }) => (
  <Alert style={{ marginBottom: 24 }} message={content} type="error" showIcon />
);

const Login: React.FC = () => {
  const [loginError, setLoginError] = useState<string>('');
  const [type, setType] = useState<string>('account');
  const [loading, setLoading] = useState<boolean>(false);
  const { initialState, setInitialState } = useModel('@@initialState');
  const { styles } = useStyles();
  const registerRef = useRef<any>(null);

  // 修改 fetchUserInfo 函数以适配统一返回格式
  const fetchUserInfo = async (): Promise<API.CurrentUser | null> => {
    try {
      // 调用全局的 fetchUserInfo 函数
      const userInfo = await initialState?.fetchUserInfo?.();

      // initialState.fetchUserInfo 应该已经处理了 BaseResponse 格式
      // 直接返回处理后的用户信息或 undefined
      return userInfo || null;
    } catch (error) {
      console.error('获取用户信息异常:', error);
      return null;
    }
  };

  const handleSubmit = async (values: API.LoginParams) => {
    if (type === 'register') {
      try {
        await registerRef.current?.submit?.();
      } catch (error) {
        console.error('注册过程中发生错误:', error);
      }
      return;
    }

    // 登录逻辑
    setLoading(true);
    setLoginError('');

    try {
      // 调用登录接口，返回统一格式 BaseResponse<LoginData>
      const response: API.LoginResult = await login({ ...values, type });

      // 判断后端返回的状态码
      if (response.code === 0) {
        // 登录成功
        message.success(response.message || '登录成功！');

        // 获取用户信息
        const userInfo = await fetchUserInfo();

        if (userInfo) {
          // 更新全局状态
          flushSync(() => {
            setInitialState((s) => ({
              ...s,
              currentUser: userInfo,
            }));
          });

          // 跳转到指定页面
          setTimeout(() => {
            const urlParams = new URL(window.location.href).searchParams;
            const redirect = urlParams.get('redirect') || '/welcome';
            history.push(redirect);
          }, 100);
        } else {
          // 获取用户信息失败，但登录可能成功了，尝试跳转到登录后页面让系统重新获取用户信息
          message.warning('登录成功，但获取用户信息失败，请刷新页面');
          setTimeout(() => {
            const urlParams = new URL(window.location.href).searchParams;
            const redirect = urlParams.get('redirect') || '/welcome';
            history.push(redirect);
          }, 1000);
        }
      } else {
        // 登录失败，显示后端返回的错误信息
        const errorMsg = response.message || '登录失败';
        message.error(errorMsg);
        setLoginError(errorMsg);

        // 记录详细错误信息用于调试
        console.error('登录失败:', {
          code: response.code,
          message: response.message,
          description: response.description
        });
      }
    } catch (error) {
      console.error('登录请求异常:', error);
      let errorMessage = '网络请求失败，请检查网络连接后重试';

      // 更详细的错误处理
      if (error instanceof Error) {
        if (error.message.includes('Network Error')) {
          errorMessage = '网络连接失败，请检查网络设置';
        } else if (error.message.includes('timeout')) {
          errorMessage = '请求超时，请稍后重试';
        } else if (error.message.includes('401')) {
          errorMessage = '认证失败，请检查账号密码';
        } else if (error.message.includes('500')) {
          errorMessage = '服务器内部错误，请稍后重试';
        }
      }

      message.error(errorMessage);
      setLoginError(errorMessage);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className={styles.container}>
      <Helmet>
        <title>{type === 'register' ? '注册' : '登录'} - {Settings.title}</title>
      </Helmet>

      <div className={styles.content}>
        <LoginForm
          contentStyle={{ minWidth: 280, maxWidth: '75vw' }}
          logo={<img alt="logo" src="/logo.svg" />}
          title="用户中心"
          subTitle="Ant Design 是西湖区最具影响力的 Web 设计规范"
          initialValues={{ autoLogin: true }}
          actions={type !== 'register' ? ['其他登录方式 :', <ActionIcons key="icons" />] : undefined}
          onFinish={async (values) => {
            await handleSubmit(values as API.LoginParams);
          }}
          submitter={{
            searchConfig: {
              submitText: type === 'register' ? '注册' : '登录',
            },
            submitButtonProps: {
              loading,
            },
          }}
        >
          <Tabs
            activeKey={type}
            onChange={(key) => {
              setType(key);
              setLoginError(''); // 切换tab时清除错误信息
            }}
            centered
            items={[
              { key: 'account', label: '登录' },
              { key: 'register', label: '注册' }
            ]}
          />

          {/* 显示登录错误信息 */}
          {loginError && type === 'account' && (
            <LoginMessage content={loginError} />
          )}

          {type === 'account' && (
            <>
              <ProFormText
                name="userAccount"
                fieldProps={{
                  size: 'large',
                  prefix: <UserOutlined />,
                  disabled: loading
                }}
                placeholder="请输入用户账号"
                rules={[
                  { required: true, message: '用户账号是必填项！' },
                  { min: 4, message: '用户账号至少4位' }
                ]}
              />
              <ProFormText.Password
                name="userPassword"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined />,
                  disabled: loading
                }}
                placeholder="请输入密码"
                rules={[
                  { required: true, message: '密码是必填项！' },
                  { min: 8, message: '密码至少8位' }
                ]}
              />
            </>
          )}

          {type === 'register' && (
            <Register
              ref={registerRef}
              onRegisterSuccess={() => {
                setType('account');
                message.success('注册成功，请登录！');
              }}
            />
          )}

          {type !== 'register' && (
            <div style={{ marginBottom: 24 }}>
              <ProFormCheckbox
                noStyle
                name="autoLogin"
                disabled={loading}
              >
                自动登录
              </ProFormCheckbox>
              <a
                style={{ float: 'right' }}
                onClick={() => {
                  message.info('请联系管理员重置密码');
                }}
              >
                忘记密码 ?
              </a>
            </div>
          )}
        </LoginForm>
      </div>

      <div className={styles.footer}>
        <Footer />
      </div>
    </div>
  );
};

export default Login;
